package hci.utils;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.xml.sax.SAXException;

public class HciPersistence {

	public static void SaveFile(ArrayList<MyPolygon> polys, String fileName, String ImageURL)
			throws XMLStreamException, IOException {

		XMLOutputFactory xof = XMLOutputFactory.newInstance();
		XMLStreamWriter xsw = xof
				.createXMLStreamWriter(new FileWriter(fileName));
		
		xsw.writeStartDocument();
		xsw.writeStartElement("document");
		xsw.writeAttribute("filename", fileName);
		xsw.writeAttribute("image", ImageURL);
		
		for (MyPolygon p : polys) {
			
			xsw.writeStartElement("polygon");
			
				xsw.writeStartElement("color");
				
					xsw.writeStartElement("red");
						xsw.writeCharacters(String.valueOf(p.getColor().getRed()));
					xsw.writeEndElement();
					
					xsw.writeStartElement("green");
						xsw.writeCharacters(String.valueOf(p.getColor().getGreen()));
					xsw.writeEndElement();
					
					xsw.writeStartElement("blue");
						xsw.writeCharacters(String.valueOf(p.getColor().getBlue()));
					xsw.writeEndElement();
			
				xsw.writeEndElement();
				
				xsw.writeStartElement("label");
					xsw.writeCharacters(p.getLabel());
				xsw.writeEndElement();
				
				for (Point c : p.getVertexs()) {
					
					xsw.writeStartElement("point");
						
						xsw.writeStartElement("x");
							xsw.writeCharacters(String.valueOf(c.getX()));
						xsw.writeEndElement();
						
						xsw.writeStartElement("y");
							xsw.writeCharacters(String.valueOf(c.getY()));
						xsw.writeEndElement();
						
					xsw.writeEndElement();
				}
				
			xsw.writeEndElement();
		}
		
		xsw.writeEndElement();
		xsw.writeEndDocument();
		xsw.flush();
		xsw.close();
	}

	public static Session restoreSession(String absolutePath) throws ParserConfigurationException, SAXException, IOException {
		
		XmlDataHandler xdh = new XmlDataHandler();
		SAXParserFactory factory = SAXParserFactory.newInstance();
		SAXParser saxp = factory.newSAXParser();
		saxp.parse(absolutePath, xdh);
		
		Session s = new Session();
		s.polygonsList = xdh.myPolygons;
		System.out.println("IMAGE FILE: " + xdh.imageFile);
		s.imageFile = xdh.imageFile;
		
		return s;
	}
}
